import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Singleton {
    private String data;
    public void setData(String content) {
        try{
            writeToFile("./io/test.txt", content);
            this.data = content;
        }
        catch(Exception e){
            System.err.println("error" + e.getMessage());
        }
    }
    public String getData() throws FileNotFoundException, IOException {
        data = readFromFile("./io/test.txt");
        return data;
    }

    private static String readFromFile(String filePath) throws FileNotFoundException, IOException {
        File file = new File(filePath);// 指定要读取的文件
        FileReader reader = new FileReader(file);// 获取该文件的输入流
        char[] bb = new char[1024];// 用来保存每次读取到的字符
        String str = "";// 用来将每次读取到的字符拼接，当然使用StringBuffer类更好
        int n;// 每次读取到的字符长度
        while ((n = reader.read(bb)) != -1) {
            str += new String(bb, 0, n);
        }
        reader.close();// 关闭输入流，释放连接
        return str;
    }
     private static void writeToFile(String filePath,String content) throws IOException {
        String writerContent = content;// 要写入的文本
        System.out.println("写入的内容：" + writerContent);
        File file = new File(filePath);// 要写入的文本文件
        if (!file.exists()) {// 如果文件不存在，则创建该文件
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file);// 获取该文件的输出流
        writer.write(writerContent);// 写内容
        writer.flush();// 清空缓冲区，立即将输出流里的内容写到文件里
        writer.close();// 关闭输出流，施放资源
    }
}
